<template>
  <div class="users_container">
    <div v-loading="loading" class="main" element-loading-text="加载中...">
      <div ref="headerRef" class="header">
        <div class="btn_group">
          <HPlainButton v-permission="'user_add'" @click="addData">新增公司</HPlainButton>
          <HPlainButton v-permission="'user_import'" @click="onImportUser">导入</HPlainButton>
          <HPlainButton v-permission="'user_export'" @click="onExportUser">导出</HPlainButton>
          <el-dropdown trigger="click">
            <HButton :disabled="selecttion.length === 0">
              批量操作
              <el-icon class="el-icon--right"><arrow-down /></el-icon>
            </HButton>
            <template #dropdown>
              <el-dropdown-menu>
                <div v-permission="'user_enabled'">
                  <el-dropdown-item @click="changeAll(1)"> 批量启用 </el-dropdown-item>
                </div>
                <div v-permission="'user_disabled'">
                  <el-dropdown-item @click="changeAll(2)"> 批量禁用 </el-dropdown-item>
                </div>
                <div v-permission="'user_delete'">
                  <el-dropdown-item @click="changeAll(3)"> 批量删除 </el-dropdown-item>
                </div>
                <div v-permission="'user_credit'">
                  <el-dropdown-item @click="creditLimitModalVisible = true">
                    批量修改授信额度
                  </el-dropdown-item>
                </div>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
        <div class="search">
          <el-select
            v-model="userListSearch.status"
            placeholder="公司状态"
            clearable
            @change="getList"
          >
            <el-option
              v-for="item in userStatus"
              :key="item.status"
              :label="item.name"
              :value="item.status"
            />
          </el-select>
          <!-- <el-select
            v-model="userListSearch.levelId"
            placeholder="公司级别"
            clearable
            :loading="getLevelOptionsLoading"
            @change="getList"
          >
            <template #header>
              <div class="select_header">
                <el-input v-model.trim="getLevelOptionsKeyword" @keyup.enter="getLevelOptions" />
                <h-plain-button @click="getLevelOptions">搜索</h-plain-button>
              </div>
            </template>
            <el-option
              v-for="item in levelOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select> -->
          <el-select
            v-model="userListSearch.userTypeId"
            placeholder="公司分类"
            clearable
            :loading="getTypeOptionsLoading"
            @change="getList"
          >
            <template #header>
              <div class="select_header">
                <el-input v-model.trim="getTypeOptionsKeyword" @keyup.enter="getTypeOptions" />
                <h-plain-button @click="getTypeOptions">搜索</h-plain-button>
              </div>
            </template>
            <el-option
              v-for="item in typeOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
          <el-input
            v-model.trim="userListSearch.userSearch"
            placeholder="公司编号/客户名称/公司手机号"
            class="input-width userSearch company-search"
            clearable
            @keyup.enter="getList"
            @clear="getList"
          />
          <el-input
            v-model.trim="userListSearch.userContactSearch"
            placeholder="联系人姓名/手机号"
            class="input-width userSearch"
            clearable
            @keyup.enter="getList"
            @clear="getList"
          />
          <HButton type="primary" @click="getList">
            <el-icon>
              <Search />
            </el-icon>
            搜索
          </HButton>
          <HButton @click="clearVlaue">
            <el-icon>
              <RefreshRight />
            </el-icon>
            重置
          </HButton>
        </div>
      </div>
      <div class="table" :style="tableStyle">
        <el-table
          ref="tableDom"
          border
          stripe
          resizable
          :data="userList"
          height="100%"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="40" fixed />

          <!-- 序号 -->
          <el-table-column label="序号" width="50" type="index" :align="'center'" fixed="left" />

          <!-- 编号 -->
          <el-table-column show-overflow-tooltip prop="code" label="编号" width="240" />

          <!-- 手机号（账号） -->
          <!-- <el-table-column
            show-overflow-tooltip
            prop="account"
            label="手机号（账号）"
            width="140"
          /> -->

          <!-- 客户名称 -->
          <el-table-column
            show-overflow-tooltip
            prop="accountName"
            label="客户名称"
            min-width="160"
          >
            <template #default="{ row }">
              <HLink @click="gouserDetail(row)">{{ row.accountName }}</HLink>
            </template>
          </el-table-column>

          <!-- 状态 -->
          <el-table-column prop="status" label="状态" width="70" fixed="right" :align="'center'">
            <template #default="scope">
              <HStatus
                v-for="item in userStatus"
                v-show="scope.row.status == item.status"
                :key="item.status"
                :type="item.status == 0 ? 'primary' : item.status == 1 ? 'success' : 'info'"
                >{{ item.name }}</HStatus
              >
            </template>
          </el-table-column>

          <!-- 主联系人 -->
          <!-- <el-table-column show-overflow-tooltip prop="username" label="主联系人" width="130" /> -->

          <!-- 主联系人手机号 -->
          <!-- <el-table-column show-overflow-tooltip prop="phone" label="主联系人手机号" width="110" /> -->

          <!-- 公司分类 -->
          <!-- <el-table-column show-overflow-tooltip prop="userType" label="公司分类" width="100" /> -->

          <!-- 知识库权限 -->
          <!-- <el-table-column
            show-overflow-tooltip
            prop="selectKnowledgeAuthor"
            label="知识库权限"
            width="154"
          >
            <template #default="scope">
              <template v-if="scope.row.selectKnowledgeAuthor">按公司分类权限查看</template>
              <template v-else>查看所有</template>
            </template>
          </el-table-column> -->

          <!-- 公司等级 -->
          <!-- <el-table-column show-overflow-tooltip prop="level" label="公司等级" width="100" /> -->

          <!-- 关联工单量 -->
          <el-table-column prop="orderNo" label="关联工单量" width="85" />

          <!-- 关联产品书 -->
          <el-table-column prop="productNo" label="关联产品数" width="85" />

          <!-- 绑定微信 -->
          <!-- <el-table-column prop="bindingWechat" label="绑定微信" width="74"
            >暂未绑定</el-table-column
          > -->

          <!-- 授信额度 -->
          <el-table-column label="授信额度" width="120">
            <template #default="{ row }">
              <span v-if="row.creditLimitType === 1">不限制</span>
              <span v-if="row.creditLimitType === 2">现付</span>
              <span v-if="row.creditLimitType === 3">￥{{ row.creditLimit.toFixed(2) }}</span>
            </template>
          </el-table-column>

          <!-- 结算期限 -->
          <el-table-column label="结算期限" width="100">
            <template #default="{ row }"> {{ row.settlementDeadline }} </template>
          </el-table-column>

          <!-- 应收账款 -->
          <el-table-column label="应收账款" width="120">
            <template #default="{ row }"> ￥{{ row.accountsReceivable.toFixed(2) }} </template>
          </el-table-column>

          <!-- 注册时间 -->
          <el-table-column show-overflow-tooltip prop="createTime" label="注册时间" width="128" />

          <!-- 更新时间 -->
          <el-table-column show-overflow-tooltip prop="updateTime" label="更新时间" width="128" />
        </el-table>
      </div>
      <div class="pagination">
        <Pagination
          ref="paginDom"
          :list_total="total"
          @size-change="getList"
          @current-change="getList(false)"
        />
      </div>

      <!-- 新增公司弹窗 -->
      <h-dialog
        v-model="addDialog"
        :title="userForm.title"
        :loading="addLoading"
        :content-padding-top="24"
      >
        <el-form
          ref="userFormRef"
          :model="userForm"
          :rules="rules"
          label-position="top"
          inline-message
          class="modal_form_content add_customer_modal_form"
          @validate="handleAddCustomerFormValidate"
        >
          <!-- 客户名称 -->
          <el-form-item label="客户名称" prop="name">
            <el-input v-model.trim="userForm.name" placeholder="请输入客户名称" clearable />
          </el-form-item>

          <!-- 公司电话 -->
          <el-form-item label="公司电话" prop="phone">
            <el-input
              v-model.trim="userForm.phone"
              placeholder="请输入公司手机号"
              clearable
              maxlength="11"
            />
          </el-form-item>

          <!-- 公司级别 -->
          <!-- <el-form-item label="公司级别" prop="levelId">
            <el-select
              v-model="userForm.levelId"
              placeholder="公司级别"
              clearable
              :loading="getLevelOptionsLoading"
            >
              <template #header>
                <div class="select_header">
                  <el-input v-model.trim="getLevelOptionsKeyword" @keyup.enter="getLevelOptions" />
                  <h-plain-button @click="getLevelOptions">搜索</h-plain-button>
                </div>
              </template>
              <el-option
                v-for="item in levelOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item> -->

          <!-- 公司分类 -->
          <el-form-item label="公司分类" prop="userTypeId">
            <el-select
              v-model="userForm.userTypeId"
              placeholder="公司分类"
              clearable
              :loading="getTypeOptionsLoading"
            >
              <template #header>
                <div class="select_header">
                  <el-input v-model.trim="getTypeOptionsKeyword" @keyup.enter="getTypeOptions" />
                  <h-plain-button @click="getTypeOptions">搜索</h-plain-button>
                </div>
              </template>
              <el-option
                v-for="item in typeOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>

          <!-- 公司编号 -->
          <el-form-item label="公司编号">
            <el-input v-model.trim="userForm.code" placeholder="如无编号系统自动生成" clearable />
          </el-form-item>

          <!-- 公司邮箱 -->
          <el-form-item label="公司邮箱" prop="email">
            <el-input v-model.trim="userForm.email" placeholder="请输入邮箱" clearable />
          </el-form-item>

          <!-- 公司状态 -->
          <el-form-item label="公司状态" class="same_line">
            <div class="switch_container">
              <el-switch v-model="userForm.status" />
              <span v-if="userForm.status">启用</span>
              <span v-else>禁用</span>
            </div>
          </el-form-item>

          <!-- 公司地址 -->
          <el-form-item label="公司地址" prop="province">
            <SingleAddress @change="handleChangeCustomerAddrs" />
          </el-form-item>

          <!-- 详细地址 -->
          <el-form-item label="详细地址" prop="address">
            <el-input
              v-model.trim="userForm.address"
              placeholder="请输入详细地址"
              clearable
              maxlength="200"
              type="textarea"
              resize="both"
              show-word-limit
            />
          </el-form-item>
        </el-form>

        <template #footer>
          <h-button is-modal type="primary" @click="saveData(userFormRef)">保存</h-button>
          <h-button is-modal @click="onAddCustomerModalCancelClick"> 取消 </h-button>
        </template>
      </h-dialog>
    </div>

    <!-- 公司导出弹窗 -->
    <h-dialog v-model="exportDialog" title="公司数据导出" :loading="exportLoading">
      <div class="export-form">
        <div class="export-title" style="margin-bottom: 18px; display: flex; column-gap: 5px">
          <span>导出数据量:</span>
          <span style="color: #007cff">{{ total }}</span>
          <span>条</span>
          <span>，若不选择筛选条件，将导出全部数据！</span>
        </div>
        <div class="export_modal_form_content">
          <!-- 公司状态 -->
          <el-select
            v-model="userListSearch.status"
            placeholder="公司状态"
            clearable
            @change="getList"
            @clear="getList"
          >
            <el-option
              v-for="item in userStatus"
              :key="item.status"
              :label="item.name"
              :value="item.status"
            />
          </el-select>

          <!-- 公司级别 -->
          <el-select
            v-model="userListSearch.levelId"
            placeholder="公司级别"
            clearable
            :loading="getLevelOptionsLoading"
            @change="getList"
            @clear="getList"
          >
            <template #header>
              <div class="select_header">
                <el-input v-model.trim="getLevelOptionsKeyword" @keyup.enter="getLevelOptions" />
                <h-plain-button @click="getLevelOptions">搜索</h-plain-button>
              </div>
            </template>
            <el-option
              v-for="item in levelOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
          <!-- 公司分类 -->
          <el-select
            v-model="userListSearch.userTypeId"
            placeholder="公司分类"
            clearable
            :loading="getTypeOptionsLoading"
            @change="getList"
            @clear="getList"
          >
            <template #header>
              <div class="select_header">
                <el-input v-model.trim="getTypeOptionsKeyword" @keyup.enter="getTypeOptions" />
                <h-plain-button @click="getTypeOptions">搜索</h-plain-button>
              </div>
            </template>
            <el-option
              v-for="item in typeOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
          <el-input
            v-model.trim="userListSearch.userSearch"
            placeholder="公司序列号/账号昵称/账号"
            clearable
            @keyup.enter="getList"
            @clear="getList"
          />
          <el-input
            v-model.trim="userListSearch.userContactSearch"
            placeholder="联系人姓名/手机号"
            clearable
            @keyup.enter="getList"
            @clear="getList"
          />
        </div>
      </div>

      <template #footer>
        <HButton is-modal type="primary" @click="onExportUserData">导出</HButton>
        <HButton is-modal @click="exportDialog = false">取消</HButton>
      </template>
    </h-dialog>

    <!-- 授信额度弹窗 -->
    <credit-limit
      v-model="creditLimitModalVisible"
      :user-ids="selecttion.map((item) => item.id)"
      @update="getList"
    />
  </div>
</template>

<script setup lang="ts">
  import { ref, reactive, onMounted, watch, CSSProperties, nextTick } from 'vue'
  import { ElMessage, ElMessageBox, FormItemProp } from 'element-plus'
  import type { FormInstance } from 'element-plus'
  import { useRoute, useRouter } from 'vue-router'
  import { Search, ArrowDown, RefreshRight } from '@element-plus/icons-vue'
  import moment from 'moment'
  import Pagination from '@/components/Pagination/index.vue'
  import SingleAddress from '@/components/business/address/single-address/SingleAddress.vue'
  import { phone } from '@/utils/validate'
  import {
    getUsersList,
    levelPageSelect,
    typePageSelect,
    addUser,
    changeStatus,
    deleteUser,
    userExportExcel,
  } from '@/api/users'
  import { useTagsViewStore } from '@/store/modules/tagsView'
  import routeComponentName from '@/config/route-component-name'
  import CreditLimit from '@/components/pages/user/detail/credit-limit/CreditLimit.vue'
  import { HMessage, HMessageBox } from '@/components/common/message'

  defineOptions({
    name: routeComponentName.customer.customerList,
  })

  // 授信额度弹窗显示状态
  const creditLimitModalVisible = ref(false)

  const route = useRoute()
  const router = useRouter()
  const addDialog = ref(false)
  const loading = ref(false)
  const exportDialog = ref(false) // 公司数据导出弹窗
  const exportLoading = ref(false) // 公司数据导出弹窗加载动画
  const headerRef = ref<HTMLDivElement | null>(null)
  const tableStyle = ref<CSSProperties>({})
  const tagsViewStore = useTagsViewStore()

  // 下拉数据
  const levelOptions = ref([]) // 级别
  const typeOptions = ref([]) // 分类

  // 用户列表
  const userList = ref<Array<UserListItem>>([])

  const tableDom = ref() // 列表dom
  const userStatus = ref([
    // 公司状态
    { status: 0, name: '启用' },
    // { status: 1, name: '冻结' },
    { status: 2, name: '禁用' },
  ])

  // 分页数据
  const paginDom = ref() // 分页dom
  const total = ref(0) // 总数目
  const userListSearch = ref({
    // 公司列表搜索条件
    page: 1,
    limit: 50,
    status: '', // 用户状态：0-正常，1-冻结，2-禁用
    levelId: '', // 用户级别ID
    userTypeId: '', // 用户分类ID
    userSearch: '', // 账号关键词搜索
    userContactSearch: '', // 联系人搜索关键词
  })

  // 公司表单数据
  const userForm = reactive({
    province: '',
    city: '',
    area: '',
    town: '',
    address: '',
    code: '',
    email: '',
    id: null,
    level: '',
    levelId: '',
    name: '',
    phone: '',
    status: true,
    title: '',
    userType: '',
    userTypeId: '',
    selectKnowledgeAuthor: false,
  })

  // 验证规则
  const rules = reactive({
    // address: [{ required: true, message: '请输入详细地址', trigger: ['change', 'blur'] }],
    name: [{ required: true, message: '请输入客户名称', trigger: ['change', 'blur'] }],
    phone: [
      { required: true, message: '请输入手机号', trigger: ['change', 'blur'] },
      { validator: phone(userForm.phone), trigger: ['change', 'blur'] },
    ],
    // province: [
    //   { required: true, message: '请选择公司地址', trigger: ['change', 'blur'] },
    //   {
    //     validator: (rule, value, callback) => {
    //       if (!userForm.province || !userForm.city || !userForm.area) {
    //         callback(new Error('请选择公司地址'))
    //       } else {
    //         callback()
    //       }
    //     },
    //     trigger: ['change', 'blur'],
    //   },
    // ],
    // userTypeId: [{ required: true, message: '请选择公司分类', trigger: 'change' }],
    email: [
      { required: false, message: '请输入邮箱', trigger: 'change' },
      {
        pattern:
          /^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,
        message: '邮箱格式不正确',
        trigger: 'change',
      },
    ],
  })

  const addLoading = ref(false)
  const userFormRef = ref<FormInstance>()

  const getLevelOptionsKeyword = ref('')
  const getLevelOptionsLoading = ref(false)
  const getLevelOptions = async () => {
    getLevelOptionsLoading.value = true
    const res = await levelPageSelect({
      limit: 0,
      name: getLevelOptionsKeyword.value,
      page: 0,
    })
    levelOptions.value = res.data.data.rows
    getLevelOptionsLoading.value = false
  }

  const getTypeOptionsKeyword = ref('')
  const getTypeOptionsLoading = ref(false)
  const getTypeOptions = async () => {
    getTypeOptionsLoading.value = true
    const res = await typePageSelect({
      limit: 0,
      name: getTypeOptionsKeyword.value,
      page: 0,
    })
    typeOptions.value = res.data.data.rows
    getTypeOptionsLoading.value = false
  }

  // 重置搜索
  const clearVlaue = () => {
    userListSearch.value = {
      page: 1,
      limit: 50,
      status: '', // 用户状态：0-正常，1-冻结，2-禁用
      levelId: '', // 用户级别ID
      userTypeId: '', // 用户分类ID
      userSearch: '', // 账号关键词搜索
      userContactSearch: '', // 联系人搜索关键词
    }
    getList()
  }

  // 获取列表数据
  const getList = (val = true) => {
    nextTick(async () => {
      if (val && paginDom.value) {
        paginDom.value.setPage()
      }
      loading.value = true
      userListSearch.value.page = paginDom.value ? paginDom.value.current : 0
      userListSearch.value.limit = paginDom.value ? paginDom.value.size : 50
      const res = await getUsersList(userListSearch.value)
      userList.value = res.data.data.rows
      total.value = parseInt(res.data.data.total)
      loading.value = false
    })
  }

  // 导入
  const onImportUser = () => {
    router.push({ path: 'userExcelImport' })
  }
  // 导出窗口
  const onExportUser = () => {
    exportDialog.value = true
  }

  // 导出公司数据
  const onExportUserData = () => {
    exportLoading.value = true
    userExportExcel(userListSearch.value).then((res) => {
      exportLoading.value = false
      ElMessage({
        type: res.data.code && !res.data.success ? 'error' : 'success',
        message: res.data.code && !res.data.success ? res.data.message : '公司数据导出成功',
        plain: true,
        duration: 5000,
        showClose: true,
      })
      if (res.data.code && !res.data.success) {
        return
      }
      const url = window.URL.createObjectURL(new Blob([res.data], { type: '.xlsx' }))
      const link = document.createElement('a')
      link.href = url
      link.download = `公司档案_${moment(new Date()).format('YYYYMMDD')}.xlsx`
      link.click()
      exportDialog.value = false
    })
  }

  // 新增公司
  const addData = () => {
    userForm.title = '新增公司'
    userForm.name = ''
    userForm.phone = ''
    userForm.levelId = ''
    userForm.userTypeId = ''
    userForm.address = ''
    userForm.code = ''
    userForm.email = ''
    userForm.status = true
    addDialog.value = true
  }

  // 保存数据
  const saveData = (formEl: FormInstance | undefined) => {
    formEl
      .validate()
      .then(() => {
        saveMethod()
      })
      .catch(() => {
        // 不可以删除该注释，否则会引起报错或警告
      })
  }

  // 保存的方法
  const saveMethod = () => {
    if (userForm.levelId) {
      levelOptions.value.forEach((item) => {
        if (userForm.levelId == item.id) {
          userForm.level = item.name
        }
      })
    }
    if (userForm.userTypeId) {
      typeOptions.value.forEach((item) => {
        if (userForm.userTypeId == item.id) {
          userForm.userType = item.name
        }
      })
    }
    const data = {
      code: userForm.code,
      email: userForm.email,
      id: userForm.id,
      level: userForm.level,
      levelId: userForm.levelId,
      name: userForm.name,
      phone: userForm.phone,
      status: userForm.status ? 0 : 2,
      province: userForm.province,
      city: userForm.city,
      area: userForm.area,
      town: userForm.town,
      address: userForm.address,
      userType: userForm.userType,
      userTypeId: userForm.userTypeId,
    }
    addLoading.value = true
    addUser(data).then((res) => {
      addLoading.value = false
      ElMessage({
        message: res.data.message,
        type: res.data.success ? 'success' : 'error',
        plain: true,
        duration: 5000,
        showClose: true,
      })
      if (res.data.success) {
        addDialog.value = false
        getList()
      }
    })
  }

  // 查看公司详情
  const gouserDetail = (obj) => {
    router.push({ path: `/user/userdetail/${obj.id}` })
  }

  // 获取表格选中的数据
  const selecttion = ref<Array<UserListItem>>([])

  /**
   * 表格选择事件
   * @param {Array<UserListItem>} val - 选中的公司
   */
  const handleSelectionChange = (val: Array<UserListItem>) => {
    selecttion.value = val
  }

  // 封装修改状态的方法
  const changeDisable = (type, name, method, arr, status, dom, getList) => {
    if (arr.length == 0) {
      ElMessage({
        message: `请选择要${type}的${name}`,
        type: 'warning',
        plain: true,
        duration: 5000,
        showClose: true,
      })
      return
    }
    ElMessageBox({
      type: type === '删除' ? 'error' : 'warning',
      title: '提示',
      message: `确定${type}选中的${name}?`,
      showCancelButton: true,
      closeOnClickModal: false,
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      autofocus: false,
      beforeClose: (action, instance, done) => {
        if (action === 'confirm') {
          instance.confirmButtonLoading = true
          instance.confirmButtonText = '加载中...'
          setTimeout(() => {
            done()
            setTimeout(() => {
              instance.confirmButtonLoading = false
            }, 0)
          }, 1000)
        } else {
          done()
        }
      },
    }).then(async () => {
      if (status != '3') {
        await method(arr, status).then((res: any) => {
          if (res.data.code === 20000) {
            HMessage.success('操作成功')
          } else {
            HMessageBox.error(res.data.message)
          }
        })
      } else {
        await method(arr).then((res: any) => {
          if (res.data.code === 20000) {
            HMessage.success('删除成功')
          } else {
            HMessageBox.error(res.data.message)
          }
        })
      }
      selecttion.value = []
      dom.clearSelection()
      getList()
    })
  }

  // 批量启用/禁用/删除
  const changeAll = (n) => {
    if (n == 1) {
      changeDisable(
        '启用',
        '公司',
        changeStatus,
        selecttion.value.map((item) => item.id),
        '0',
        tableDom.value,
        getList,
      )
    }
    if (n == 2) {
      changeDisable(
        '禁用',
        '公司',
        changeStatus,
        selecttion.value.map((item) => item.id),
        '2',
        tableDom.value,
        getList,
      )
    }
    if (n == 3) {
      changeDisable(
        '删除',
        '公司',
        deleteUser,
        selecttion.value.map((item) => item.id),
        '3',
        tableDom.value,
        getList,
      )
    }
  }

  const addCustomerFormValidateResult = ref({
    name: true,
    phone: true,
    userTypeId: true,
    address: true,
    addrs: true,
  })

  const handleAddCustomerFormValidate = (prop: FormItemProp, isValid: boolean) => {
    addCustomerFormValidateResult.value[prop as string] = isValid
  }

  const onAddCustomerModalCancelClick = () => {
    addDialog.value = false
    addCustomerFormValidateResult.value = {
      name: true,
      phone: true,
      userTypeId: true,
      address: true,
      addrs: true,
    }
  }

  const handleChangeCustomerAddrs = (param: {
    province: string
    city: string
    area: string
    town: string
  }) => {
    userForm.province = param.province
    userForm.city = param.city
    userForm.area = param.area
    userForm.town = param.town
  }

  const setTableStyle = () => {
    const headerHeight = headerRef.value ? headerRef.value.scrollHeight : 0
    tableStyle.value.maxHeight = `calc(100% - 24px - 28px - ${headerHeight}px)`
  }

  watch(
    () => route.name,
    (value) => {
      if (route.query.type == 'new') {
        addData()
      }
      if (value === 'userList') {
        getList()
        getLevelOptions()
        getTypeOptions()
      }
    },
    { immediate: true },
  )

  watch(
    () => tagsViewStore.getReloadPages,
    (value) => {
      if (value.includes(route.path)) {
        window.removeEventListener('resize', setTableStyle)
      }
    },
    { deep: true },
  )

  onMounted(() => {
    getList()
    getLevelOptions()
    getTypeOptions()
    setTableStyle()
    window.addEventListener('resize', setTableStyle)
  })
</script>

<style scoped lang="scss">
  @import './index';
</style>
